<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <el-row v-show="showSearch">
        <el-form ref="queryRef" :inline="true" :model="state.queryForm" @keyup.enter="getDataList">
          <el-form-item label="村名称" prop="name">
            <el-input v-model="state.queryForm.name" :placeholder="$t('sysuser.inputUsernameTip')"
                      clearable/>
          </el-form-item>
          <el-form-item>
            <el-button icon="Search" type="primary" @click="getDataList">{{
                $t('common.queryBtn')
              }}
            </el-button>
            <el-button icon="Refresh" @click="resetQuery">{{ $t('common.resetBtn') }}</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <el-row>
        <div class="mb8" style="width: 100%">
          <el-button v-auth="'sys_user_add'" icon="folder-add" type="primary"
                     @click="villageDialogRef.openDialog()">
            {{ $t('common.addBtn') }}
          </el-button>
          <!-- <el-button plain v-auth="'sys_user_add'" class="ml10" icon="upload-filled" type="primary" @click="excelUploadRef.show()">
            {{ $t('common.importBtn') }}
          </el-button>

          <el-button plain v-auth="'sys_user_del'" :disabled="multiple" class="ml10" icon="Delete" type="primary" @click="handleDelete(selectObjs)">
            {{ $t('common.delBtn') }}
          </el-button> -->

          <!-- <right-toolbar
            v-model:showSearch="showSearch"
            :export="'sys_user_export'"
            @exportExcel="exportExcel"
            @queryTable="getDataList"
            class="ml10 mr20"
            style="float: right"
          /> -->
        </div>
      </el-row>
      <el-table v-loading="state.loading" :data="state.dataList" @selection-change="handleSelectionChange"
                row-key="userId" border :cell-style="tableStyle.cellStyle"
                :header-cell-style="tableStyle.headerCellStyle">
        <el-table-column :selectable="handleSelectable" type="selection" width="40"/>
        <el-table-column :label="$t('village.index')" type="index" width="60" fixed="left"/>
        <el-table-column :label="$t('village.name')" prop="name" show-overflow-tooltip></el-table-column>

        <el-table-column :label="$t('village.doctor')" prop="doctorName"
                         show-overflow-tooltip></el-table-column>
        <el-table-column label="关联专病医生" prop="zbDoctor"
                         show-overflow-tooltip>
          <template #default="scope">
            <template v-for="item in ZBDoctorList">
              {{ scope.row.zbDoctor === item.userId ? item.name : "" }}
            </template>
          </template>
        </el-table-column>


        <el-table-column label="专病医生助理" prop="zlId"  show-overflow-tooltip>
          <template #default="scope">
            <template v-for="item in ZLDoctorList">
              {{ scope.row.zlId === item.userId ? item.name : "" }}
            </template>
          </template>
        </el-table-column>
        <el-table-column label="排序" prop="villageSort" show-overflow-tooltip></el-table-column>

        <el-table-column :label="$t('village.status')" prop="status" show-overflow-tooltip>
          <template #default="scope">
            <el-tag v-if="scope.row.villageStatus === '1'" type="success">启用</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>

        <el-table-column :label="$t('common.action')" width="200" fixed="right">
          <template #default="scope">
            <!-- 修改信息 -->
            <el-button v-auth="'sys_user_edit'" icon="edit-pen" text type="primary"
                       @click="villageDialogRef.openDialog(scope.row)">
              {{ $t('common.editBtn') }}
            </el-button>
            <!-- 删除用户 -->
            <el-tooltip :content="$t('sysuser.deleteDisabledTip')" :disabled="scope.row.userId !== '1'"
                        placement="top">
								<span style="margin-left: 12px">
									<el-button icon="delete" v-auth="'sys_user_del'"
                             :disabled="scope.row.username === 'admin'" text type="primary"
                             @click="handleDelete([scope.row.userId])">{{ $t('common.delBtn') }}
									</el-button>
								</span>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-bind="state.pagination" @current-change="currentChangeHandle" @size-change="sizeChangeHandle">
      </pagination>
    </div>

    <village-form ref="villageDialogRef" @refresh="getDataList(false)"/>

    <upload-excel ref="excelUploadRef" :title="$t('sysuser.importUserTip')"
                  temp-url="/admin/sys-file/local/file/user.xlsx" url="/admin/user/import"
                  @refreshDataList="getDataList"/>
  </div>
</template>

<script lang="ts" name="systemUser" setup>
import {getAllZbAideDoctor, getAllZbDoctor, villageList} from '/@/api/information/village';

import {BasicTableProps, useTable} from '/@/hooks/table';
import {useMessage, useMessageBox} from '/@/hooks/message';
import {useI18n} from 'vue-i18n';

// 动态引入组件
const VillageForm = defineAsyncComponent(() => import('./form.vue'));
const QueryTree = defineAsyncComponent(() => import('/@/components/QueryTree/index.vue'));
const PopoverInput = defineAsyncComponent(() => import('/@/components/PopoverInput/index.vue'));

const {t} = useI18n();
const ZBDoctorList = ref<any[]>([]);
const ZLDoctorList = ref<any[]>([]);
// 定义变量内容
const villageDialogRef = ref();
const excelUploadRef = ref();
const queryRef = ref();
const showSearch = ref(true);

// 多选rows
const selectObjs = ref([]) as any;
// 是否可以多选
const multiple = ref(true);

// 定义表格查询、后台调用的API
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {
    name: '',
  },

  pageList: villageList,
});
const {getDataList, currentChangeHandle, sizeChangeHandle, downBlobFile, tableStyle} = useTable(state);

const getdoctorList = () => {
  getAllZbDoctor().then((res) => {
    ZBDoctorList.value = res.data;
  });

  getAllZbAideDoctor().then((res) => {
    ZLDoctorList.value = res.data;
  });
}

onMounted(() => {
  getdoctorList()
});

// 清空搜索条件
const resetQuery = () => {
  queryRef.value?.resetFields();
  state.queryForm.deptId = '';
  getDataList();
};

// 点击树
const handleNodeClick = (e: any) => {
  state.queryForm.deptId = e.id;
  getDataList();
};

// 导出excel
const exportExcel = () => {
  downBlobFile('/admin/user/export', Object.assign(state.queryForm, {ids: selectObjs}), 'users.xlsx');
};

// 是否可以多选
const handleSelectable = (row: any) => {
  return row.username !== 'admin';
};

// 多选事件
const handleSelectionChange = (objs: { userId: string }[]) => {
  selectObjs.value = objs.map(({userId}) => userId);
  multiple.value = !objs.length;
};

// 删除操作
const handleDelete = async (ids: string[]) => {
  try {
    await useMessageBox().confirm(t('common.delConfirmText'));
  } catch {
    return;
  }

  try {
    await delObj(ids);
    getDataList();
    useMessage().success(t('common.delSuccessText'));
  } catch (err: any) {
    useMessage().error(err.msg);
  }
};

//表格内开关 (用户状态)
const changeSwitch = async (row: any) => {
  // 不修改密码
  row.password = undefined;
  row.phone = undefined;
  await putObj(row);
  useMessage().success(t('common.optSuccessText'));
  getDataList();
};

//修改用户密码
const changePassword = async (row: any) => {
  if (!inputPassword.value || inputPassword.value.length < 6 || inputPassword.value.length > 20) {
    useMessage().error(t('sysuser.inputPasswordTip'));
    return;
  }

  row.phone = undefined;
  row.password = inputPassword.value;
  await putObj(row);
  useMessage().success(t('common.optSuccessText'));
  getDataList();
};
</script>
